package com.adtouch.login;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.barcodescanner.MainActivity;
import com.example.barcodescanner.R;

public class LoginActivity extends Activity {
	
	String URL = "http://adtouch.cloudfoundry.com/";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        final Button login = (Button) findViewById(R.id.login);
        
        login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				 /*Toast toast = Toast.makeText(getApplicationContext(), "Login Clicked",
				 Toast.LENGTH_LONG);
				 toast.show();*/
				
				EditText editEmail  = (EditText) findViewById(R.id.email);
				String email = editEmail.getText().toString();
				EditText editPassword  = (EditText) findViewById(R.id.password);
				String password = editPassword.getText().toString();
				
                callWebService(email,password); 
				
				/*Intent browserIntent = new Intent(getApplicationContext(),
							MainActivity.class);
					startActivity(browserIntent);*/
				
				
			}

		});

        
    }
    
    public void callWebService(String email,String password){  
        HttpClient httpclient = new DefaultHttpClient();  
        String q=URL + "rest/user/"+email;
        try{
        
        	
        	MessageDigest m = null;
        	try {
        	m = MessageDigest.getInstance("MD5");
        	} catch (NoSuchAlgorithmException e1) {
        	// TODO Auto-generated catch block
        	e1.printStackTrace();
        	}
        	m.reset();
        	m.update(password.getBytes());
        	byte[] digest = m.digest();
        	BigInteger bigInt = new BigInteger(1, digest);
        	String hashtext = bigInt.toString(16);
        	// Now we need to zero pad it if you actually want the full 32
        	// chars.
        	while (hashtext.length() < 32) {
        	hashtext = "0" + hashtext;
        	}   	
        	
/*        	byte[] pass = password.getBytes("UTF-8");
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] digest = m.digest(pass);
        password = digest.toString();
        //String password1 = new String(digest,"UTF-8");*/
        String temp= email+":"+hashtext;
        byte[] encoded = Base64.encodeBase64(temp.getBytes());
        
        HttpGet request = new HttpGet(q);
       // System.out.println("url is" + URL + q);
        
        String result;
        
        temp = new String(encoded,"UTF-8");
        
        temp = "Basic " + temp; 
        
        request.addHeader("Authorization", temp);
        //request.addHeader("Content-type","applicaiton/json");
        request.addHeader("Accept","application/json");
        
        
        ResponseHandler<String> handler = new BasicResponseHandler();  
          
            result = httpclient.execute(request, handler);  
            
            System.out.println(result);
            
            
   				JSONObject json = new JSONObject(result);
   			     
   				String validation = (String)json.get("approval");
   				
   				if (validation.equalsIgnoreCase("approved"))
   				{
   					Intent browserIntent = new Intent(getApplicationContext(),
   							MainActivity.class);
   					startActivity(browserIntent);

   					
   				}
   				else
   				{
   				 Toast toast = Toast.makeText(getApplicationContext(), "Invalid Username/Password",
   	      				 Toast.LENGTH_LONG);
   	      				 toast.show();
   				}
   				
   				
        } catch (Exception e) {  
        	
                 e.printStackTrace();
        }  
        httpclient.getConnectionManager().shutdown();  
        //Log.i(tag, result);  
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }
}
